__author__ = 'Administrator'

import os,csv
import pandas as pd

def runCalcPNL(sdate,edate):
	path = "D:\\log\\netValue\\logicCheck\\"
	datelist = sorted(os.listdir(path))
	output_path = "d:\\temp"
	fd = open(output_path+"\\prod14.pnl.total.calc.csv","w")
	fd.write("#date,calc_pnl,stk_pnl,f_pnl\n")
	cpnl = 0
	l_nv,nv,stk_pnl,f_pnl=0,0,0,0
	for f in datelist:
		cpnl = 0
		f_pnl = 0
		stk_pnl = 0
		if "prod14" not in f:
			continue
		date = f[0:8]
		if sdate == edate:
			date = sdate
		elif date < sdate or date > edate:
			continue
		fname =path+f
		table = csv.reader(open(fname,'r'))
		for line in table:
			if line[0] == "currentFuturePnl":
				f_pnl += float(line[3])
			elif line[0] == "currentFutureComm":
				f_pnl -= abs(float(line[3]))
			elif line[0] == "totalStockComm":
				stk_pnl -= abs(float(line[3]))
			elif line[0] == "currentStockPnlExcludeETF":
				stk_pnl += float(line[3])
			elif line[0] == "netValue":
				nv = float(line[3])
		cpnl = nv - l_nv
		l_nv = nv
		fd.write("%s,%.2f,%.2f,%.2f\n" % (date,cpnl,stk_pnl,f_pnl))
	fd.close()

def getHoldPNL(type,table,dpx_df):
	pnl= 0
	for line in table:
		tk = line[0]
		shr = line[1]
		cls_1 = line[2]
		if type == 2:
			cls = dpx_df.loc[tk,"SETTLE"]
			if tk[0:2] == 'IF' or tk[0:2] == "IH":
				'''
				shr is a negative number
				'''
				pnl += shr * (cls - cls_1) * 300
			elif tk[0:2] == "IC":
				pnl += shr * (cls - cls_1) * 200
		elif type == 1:
			if tk not in dpx_df.index.tolist():
				continue
			cls = dpx_df.loc[tk,"CLOSE"]
			pnl += shr*(cls-cls_1)
	return pnl

def getTradePNL(type,table,dpx_df):
	pass

def runPNLfromFiles(sdate,edate):
	h_path = "P:\\NetValue\\production14\\portfolio\\actHolding\\"
	datelist = sorted(os.listdir(h_path))
	output_path = "d:\\temp"
	fd = open(output_path+"\\prod14.pnl.file.calc.csv","w")
	fd.write("#date,calc_pnl,stk_pnl,f_pnl\n")
	cpnl = 0
	for f in datelist:
		stk_pnl,stk_t_pnl,stk_hold_pnl,f_pnl,f_t_pnl,f_h_pnl = 0,0,0,0,0,0
		stk_com,stk_com_rate=0,0.0003
		f_com,f_com_rate = 0,0.00004
		cpnl = 0
		f_pnl = 0
		stk_pnl = 0
		if "BOD" not in f:
			continue
		date = f[0:8]
		if sdate == edate:
			date = sdate
		elif date < sdate or date > edate:
			continue
		fname =h_path+f
		table = csv.reader(open(fname,'r'))
		f_h_pnl = getHoldPNL(2,table)
		f_t_pnl = getTradePNL(2,table)
		stk_hold_pnl = getHoldPNL(1,table)
		stk_t_pnl = getTradePNL(1,table)
		fd.write("%s,%.2f,%.2f,%.2f\n" % (date,cpnl,stk_pnl,f_pnl))
	fd.close()

if __name__ == '__main__':
	runCalcPNL("20160427","20160705")
